package com.zzl.boot.bigevent.utils;

import java.io.*;
import java.util.Date;
import java.util.Random;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.BasicCredentials;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.common.comm.SignVersion;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AliOss {
    /** 生成一个唯一的 Bucket 名称 */
    static private final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";// 设置 OSS Endpoint
    static private final String BUCKET_Name = "bigevent-zzl";// 设置Bucket 名称
    static private final String REGION = "cn-beijing";// 替换 Bucket 区域
    public static String generateUniqueBucketName(String prefix) {
        // 获取当前时间戳
        String timestamp = String.valueOf(System.currentTimeMillis());
        // 生成一个 0 到 9999 之间的随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000); // 生成一个 0 到 9999 之间的随机数
        // 连接以形成一个唯一的 Bucket 名称
        return prefix + "-" + timestamp + "-" + randomNum;
    }

    public static String uploadFile(String objectName,InputStream inputStream) throws com.aliyuncs.exceptions.ClientException {
        // 从环境变量中获取访问凭证。运行本代码示例之前，请先配置环境变量
//        EnvironmentVariableCredentialsProvider credentialsProvider =
//                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
//        log.info("accessKeyId:"+credentialsProvider.getCredentials().getAccessKeyId());
//        log.info("accessKeySecret:"+credentialsProvider.getCredentials().getSecretAccessKey());
        // 创建 OSSClient 实例
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
//        OSS ossClient = OSSClientBuilder.create()
//                .endpoint(ENDPOINT)
//                .credentialsProvider(credentialsProvider)
//                .clientConfiguration(clientBuilderConfiguration)
//                .region(REGION)
//                .build();

        // 修改后的代码
        String accessKeyId = "LTAI5tJSYkqPTS6q3mHu6PzB";
        String accessKeySecret = "1gyafIAnWy1OQDye2yaWf3cENAa3q1";
// 创建OSSClient实例时直接使用硬编码的凭证

        // 创建BasicCredentials对象并设置到client
        BasicCredentials credentials = new BasicCredentials(accessKeyId, accessKeySecret, null);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(ENDPOINT)
                .credentialsProvider(new DefaultCredentialProvider(credentials))
                //.clientConfiguration(clientBuilderConfiguration)
                .region(REGION)
                .build();
        try {
            // 1. 创建存储空间（Bucket）
            //ossClient.createBucket(ENDPOINT);
            //System.out.println("1. Bucket " + ENDPOINT + " 创建成功。");
            // 2. 上传文件
            //String objectName = "001.png";
            //String content = "Hello OSS";
            ossClient.putObject(BUCKET_Name, objectName, inputStream);
            System.out.println("2. 文件 " + objectName + " 上传成功。");
            // 3. 下载文件
//            OSSObject ossObject = ossClient.getObject(bucketName, objectName);
//            InputStream contentStream = ossObject.getObjectContent();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(contentStream));
//            String line;
//            System.out.println("3. 下载的文件内容：");
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line);
//            }
//            contentStream.close();
            // 4. 列出文件
            ObjectListing objectListing = ossClient.listObjects(BUCKET_Name);
            for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
                System.out.println(" - " + objectSummary.getKey() + " (大小 = " + objectSummary.getSize() + ")");
            }
            System.out.println(objectListing.getObjectSummaries());
            // 5. 删除文件
//            ossClient.deleteObject(bucketName, objectName);
//            System.out.println("5. 文件 " + objectName + " 删除成功。");
            // 6. 删除存储空间（Bucket）
//            ossClient.deleteBucket(bucketName);
//            System.out.println("6. Bucket " + bucketName + " 删除成功。");
        } catch (OSSException oe) {
            log.info("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.info("Error Message:" + oe.getErrorMessage());
            log.info("Error Code:" + oe.getErrorCode());
            log.info("Request ID:" + oe.getRequestId());
            log.info("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
             log.info("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.info("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10);
        String url = ossClient.generatePresignedUrl(BUCKET_Name, objectName, expiration).toString();
        //return "https://"+BUCKET_Name+"."+ENDPOINT.substring(ENDPOINT.lastIndexOf("/")+1)+"/"+objectName;
        return url;
    }
}

